package com.agrm.rabc.controller;


import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.rabc.dto.Menu;
import com.agrm.rabc.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api/v1/menus", produces = MediaType.APPLICATION_JSON_VALUE)
public class MenuApi {
    private MenuService menuService;

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    @GetMapping("/tree")
    public ResponseResult findTree() {
        //查询所有根节点
        List<Menu> roots = menuService.findTree();
        return ResponseResult.okResult(roots);
    }

    @PostMapping
    public ResponseResult save(@RequestBody Menu menu) {
        boolean success = menuService.save(menu);
        if (success) {
            return ResponseResult.okResult(menu);
        } else {
            return ResponseResult.errorResult(-1,"保存菜单失败");
        }
    }

    @PutMapping
    public ResponseResult update(@RequestBody Menu menu) {
        boolean success = menuService.update(menu);
        if (success) {
            return ResponseResult.okResult(menu);
        } else {
            return ResponseResult.errorResult(-1,"修改菜单失败");
        }
    }

    @DeleteMapping
    public ResponseResult deleteByIds(@RequestBody Integer[] ids) {
        int count = this.menuService.deleteByIds(List.of(ids));
        if (count > 0) {
            return ResponseResult.okResult(count);
        } else {
            return ResponseResult.errorResult(-1,"删除菜单失败");
        }
    }
}
